package com.ikingtech.platform.service.wechat.mini.controller;

import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.wechat.embedded.mini.*;
import com.ikingtech.framework.sdk.wechat.embedded.mini.resposne.WechatMiniResponseSession;
import com.ikingtech.framework.sdk.wechat.mini.api.WechatMiniApi;
import com.ikingtech.framework.sdk.wechat.mini.api.WechatMiniConfigLoader;
import com.ikingtech.framework.sdk.wechat.mini.model.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
@ApiController(value = "/wechat/mini", name = "微信管理-微信小程序管理", description = "微信管理-微信小程序管理")
public class WechatMiniController implements WechatMiniApi {

    private final WechatMiniRequestBuilder wechatMiniRequestBuilder;

    private final WechatMiniConfigLoader configLoader;

    /**
     * 发送订阅消息
     * @param sendMessageParam 发送消息参数
     * @return 操作结果
     */
    @Override
    public R<Object> sendSubscribeMessage(WechatMiniSendMessageParamDTO sendMessageParam) {
        // 构建微信请求对象
        this.wechatMiniRequestBuilder.build(this.loadConfig(sendMessageParam.getWechatMiniId()))
                // 发送订阅消息
                .sendSubscribeMessage(WechatMiniSendSubscribeMessageArgs.builder()
                        .templateId(sendMessageParam.getTemplateId())
                        .openId(sendMessageParam.getOpenId())
                        .redirectTo(sendMessageParam.getRedirectTo())
                        .params(sendMessageParam.getParam())
                        .build());
        return R.ok();
    }

    /**
     * 通过授权码换取微信小程序用户信息
     * @param exchangeCodeParam 交换code参数
     * @return 换取的微信小程序用户信息
     */
    @Override
    public R<WechatMiniUserInfoDTO> exchangeCode(WechatMiniExchangeCodeParamDTO exchangeCodeParam) {
        // 构建微信小程序请求对象
        WechatMiniResponseSession wechatMiniSessionInfo = this.wechatMiniRequestBuilder.build(this.loadConfig(exchangeCodeParam.getWechatMiniId())).exchangeCode(exchangeCodeParam.getCode());
        // 创建微信小程序用户信息对象
        WechatMiniUserInfoDTO userInfo = new WechatMiniUserInfoDTO();
        // 设置微信小程序用户信息
        userInfo.setUnionId(wechatMiniSessionInfo.getUnionid());
        userInfo.setOpenid(wechatMiniSessionInfo.getOpenid());
        userInfo.setSessionKey(wechatMiniSessionInfo.getSessionKey());
        // 返回换取的微信小程序用户信息
        return R.ok(userInfo);
    }

    /**
     * 根据授权码获取手机号
     * @param queryParam 查询参数
     * @return 返回手机号信息
     */
    @Override
    public R<WechatMiniPhoneDTO> getPhoneByCode(WechatMiniPhoneQueryParamDTO queryParam) {
        // 构建微信小程序请求
        WechatMiniUserPhoneInfo userPhoneInfo = this.wechatMiniRequestBuilder.build(this.loadConfig(queryParam.getWechatMiniId())).getPhone(queryParam.getCode());
        // 创建手机号对象
        WechatMiniPhoneDTO phone = new WechatMiniPhoneDTO();
        // 设置手机号
        phone.setPhoneNo(userPhoneInfo.getPhone());
        // 设置手机号（无国家码）
        phone.setPurePhoneNo(userPhoneInfo.getPurePhone());
        // 设置国家码
        phone.setCountryCode(userPhoneInfo.getCountryCode());
        // 返回手机号信息
        return R.ok(phone);
    }

    /**
     * 生成微信小程序二维码
     *
     * @param generateParam 二维码生成参数
     * @return 二维码的Base64字符串
     */
    @Override
    public R<String> qrcode(WechatMiniQrcodeGenerateParamDTO generateParam) {
        // 构建微信小程序请求参数
        String qrcodeBase64Str = this.wechatMiniRequestBuilder.build(this.loadConfig(generateParam.getWechatMiniId()))
                .qrcodeGenerate(WechatMiniQrcodeGenerateArgs.builder()
                        .page(generateParam.getPage())
                        .width(generateParam.getWidth())
                        .param(generateParam.getParam())
                        .version(generateParam.getVersion())
                        .build());
        // 返回二维码的Base64字符串
        return R.ok(qrcodeBase64Str);
    }

    /**
     * 生成微信小程序的链接
     * @param generateParam 生成链接的参数
     * @return 生成的链接
     */
    @Override
    public R<String> urlLink(WechatMiniUrlLinkGenerateParamDTO generateParam) {
        // 通过微信小程序ID加载配置
        String urlLink = this.wechatMiniRequestBuilder.build(this.loadConfig(generateParam.getWechatMiniId()))
                // 生成链接
                .urlLinkGenerate(WechatMiniUrlLinkGenerateArgs.builder()
                        .page(generateParam.getPage())
                        .param(generateParam.getParam())
                        .build());
        return R.ok(urlLink);
    }

    /**
     * 获取订阅消息模板列表
     * @param wechatMiniId 微信小程序ID
     * @return 返回订阅消息模板列表
     */
    @Override
    public R<List<WechatMiniSubscribeMessageTemplateDTO>> listSubscribeMessageTemplate(String wechatMiniId) {
        // 构建微信小程序请求
        List<WechatMiniSubscribeMessageTemplateInfo> messageTemplates = this.wechatMiniRequestBuilder
                .build(this.loadConfig(wechatMiniId))
                .listSubscribeMessageTemplate();
        // 将模板信息转换为订阅消息模板DTO对象
        return R.ok(Tools.Coll.convertList(messageTemplates, templateInfo -> {
            WechatMiniSubscribeMessageTemplateDTO template = new WechatMiniSubscribeMessageTemplateDTO();
            template.setId(templateInfo.getTemplateId());
            template.setWechatMiniId(wechatMiniId);
            template.setName(templateInfo.getTemplateTitle());
            template.setTitle(templateInfo.getTemplateTitle());
            template.setContent(templateInfo.getContent());
            template.setType(templateInfo.getType());
            template.setTypeName(templateInfo.getType().description);
            template.setParams(templateInfo.getParams());
            return template;
        }));
    }

    /**
     * 加载微信小程序配置
     * @param wechatMiniId 微信小程序ID
     * @return 微信小程序配置对象
     */
    private WechatMiniConfig loadConfig(String wechatMiniId) {
        return Tools.Bean.copy(this.configLoader.load(wechatMiniId), WechatMiniConfig.class);
    }
}
